<?php


namespace App\Services;


use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\MeetingTemplate;
use App\Services\Dao\MeetingTplDao;
use App\Services\Formatter\MeetingTplFormatter;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Codec\Json;

class MeetingTplService
{
    /**
     * @Inject
     * @var MeetingTplDao
     */
    protected $meetingTplDao;

    /**
     * @Inject
     * @var MeetingTplFormatter
     */
    protected $tplFormatter;

    /**
     * note:获取用户所有模板
     * @param int $userId
     * @param int $limit
     * created by: lhw at 9/1/2022 1:55 下午
     * @return array
     */
    public function findAllTplByUserId(int $userId, int $limit = 10): array
    {
        $result = $this->meetingTplDao->findAllByUserId($userId, $limit);
        $items = $this->tplFormatter->formatList($result->items());
        return [$result->total(), $items];
    }

    /**
     * note:存储模板信息
     * @param int $tplId
     * @param int $userId
     * @param array $data
     * created by: lhw at 9/1/2022 2:20 下午
     * @return bool
     */
    public function store(int $tplId, int $userId, array $data): bool
    {
        if ($tplId > 0) {
            $model = $this->meetingTplDao->findInfoById($tplId);
            if ($model->user_id !== $userId) {
                throw new BusinessException(ErrorCode::AUTH_INVALID, ErrorCode::getMessage(ErrorCode::AUTH_INVALID));
            }
        } else {
            $model = new MeetingTemplate();
            $model->user_id = $userId;
        }
        $model->title = $data['title'];
        $model->content = $data['content'];
        $model->user_limit = $data['userLimit'];
        $model->sign_rules = Json::encode($data['signRules']);
        $model->sign_fields = isset($data['signFields']) ? Json::encode($data['signFields']) : '';
        $model->sign_type = $data['signType'];
        $model->status = $data['status'];

        return $model->save();
    }

    /**
     * note:删除模板
     * @param int $tplId
     * @param int $userId
     * @return bool|int|mixed|null
     * @throws \Exception
     * created by: lhw at 9/1/2022 3:22 下午
     */
    public function del(int $tplId, int $userId)
    {
        $model = $this->meetingTplDao->findInfoById($tplId);
        if (empty($model)) {
            throw new BusinessException(ErrorCode::MEETING_TPL_NOT_EXIST, ErrorCode::getMessage(ErrorCode::MEETING_TPL_NOT_EXIST));
        }
        if ($model->user_id !== $userId) {
            throw new BusinessException(ErrorCode::AUTH_INVALID, ErrorCode::getMessage(ErrorCode::AUTH_INVALID));
        }
        return $model->delete();
    }
}
